package com.kgc.service.impl;

import com.github.pagehelper.PageInfo;
import com.kgc.dao.NewsEsDao;
import com.kgc.dao.NewsMapper;
import com.kgc.entity.News;
import com.kgc.service.NewsService;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class NewsServiceImpl implements NewsService {


    private int pages;
    private boolean temp = true;
    @Autowired
    private NewsMapper newsMapper;
    @Autowired
    private NewsEsDao newsEsDao;
    @Autowired
    private ElasticsearchRestTemplate ert;

    private static final Logger logger = LoggerFactory.getLogger(NewsServiceImpl.class);

    @Override
    public void allNews() {

        newsEsDao.saveAll(newsMapper.getAllNews());
    }

    @Override
    public int addNews(News news) {
        temp = !temp;
        return newsMapper.addNews(news);
    }

    @Override
    public int updateNews(News news) {
        temp = !temp;
        return newsMapper.updateNews(news);
    }

    @Override
    public int deleteNews(Integer id) {
        temp = !temp;
        return newsMapper.deleteNews(id);
    }

    @Override
    public News getNewsById(Integer id) {
        return newsMapper.getNewsById(id);
    }

    @Override
    public List<News> getFrontFiveNews() {
        return newsMapper.getFrontFiveNews();
    }


    @Override
    public News getNewsByTitle(String title) {
        return newsMapper.getNewsByTitle(title);
    }

    public void initData() {
        newsEsDao.deleteAll();
        allNews();
        System.out.println("将数据库中全部数据导入elasticsearch");
        temp = !temp;
    }

    @Override
    public PageInfo<News> selectNewsByTitle(Map<String, Object> params) {
        if (temp) {
            initData();
        }
        NativeSearchQueryBuilder nsqb = new NativeSearchQueryBuilder();
        if (params.containsKey("searchTitle")) {
            nsqb.withQuery(QueryBuilders.matchQuery("title", params.get("searchTitle")));
        } else {
            nsqb.withQuery(QueryBuilders.matchAllQuery());
            System.out.println("无条件搜索");
        }
        // 设置排序字段和顺序
        String sortField = "createTime"; // 假设创建时间字段名为 createTime
        SortOrder sortOrder = SortOrder.ASC; // 默认升序
        if (params.containsKey("orderBy")) {
            String orderBy = (String) params.get("orderBy");
            if (orderBy.equals("按时间倒序")) {
                sortOrder = SortOrder.DESC; // 降序
            }
        }
        nsqb.withSort(SortBuilders.fieldSort(sortField).order(sortOrder))
                .withPageable(PageRequest.of((int) params.get("pageNum") - 1, (int) params.get("pageSize")));
        HighlightBuilder hb = new HighlightBuilder();
        hb.field("title");
        hb.preTags("<span style='color:red'>");
        hb.postTags("</span>");
        nsqb.withHighlightBuilder(hb);
        SearchHits<News> searchHits = ert.search(nsqb.build(), News.class);
        PageInfo<News> pageInfo = new PageInfo<>();
        ArrayList<News> list = new ArrayList<>();
        for (SearchHit<News> searchHit : searchHits.getSearchHits()) {
            News product = searchHit.getContent();
            if (params.containsKey("searchTitle")) {
                product.setTitle(searchHit.getHighlightField("title").get(0));
            }
            list.add(product);
        }
        pageInfo.setList(list);
        pageInfo.setPageNum((int) params.get("pageNum"));
        pageInfo.setPageSize((int) params.get("pageSize"));
        pageInfo.setTotal(searchHits.getTotalHits());
        pages = (int) searchHits.getTotalHits() % pageInfo.getPageSize() > 0 ? (int) searchHits.getTotalHits() / pageInfo.getPageSize() + 1 : (int) searchHits.getTotalHits() / pageInfo.getPageSize();
        pageInfo.setPages(pages);
        System.out.println("搜索到的数据条数" + pageInfo.getTotal());
        System.out.println("搜索到的数据页数" + pageInfo.getPages());
        return pageInfo;
    }

}
